<template>
  <div id="app">
    <nav class="navbar navbar-expand-md navbar-dark bg-dark shadow">
      <a href="#/" class="navbar-brand">Agent</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false" aria-label="Toggle Navigation"><span class="navbar-toggler-icon"></span></button>

      <div class="collapse navbar-collapse" id="main-navbar">
        <!-- <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <a href="#/" class="nav-link">Home <span class="sr-only">(current)</span></a>
          </li>
        </ul> -->
        <!-- <form class="form-inline my-2 my-lg-0">
          <input type="text" class="form-control mr-sm-2" placeholder="Search" aria-label="Search">
          <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
        </form> -->
      </div>
    </nav>

    <main role="main" class="container mt-4">
      <router-view></router-view>
    </main>
  </div>
</template>

<script>
import {
  getExtraSpaceToScroll
} from './helpers/IframeEventHelper'
import {
  ON_AGENT_MESSAGE_RECEIVED,
  ON_UNREAD_MESSAGE_CLICK
} from './constants/widgetBusEvents'
import { IFrameHelper } from './helpers/utils'
import bus from './helpers/bus'

export default {
  name: 'App',
  mounted () {
    this.registerUnreadEvents()
  },
  methods: {
    registerUnreadEvents () {
      window.addEventListener('message', e => {
        console.log(e)
      })
      bus.$on(ON_AGENT_MESSAGE_RECEIVED, () => {
        const { name: routeName } = this.$route
        if (this.isWidgetOpen && routeName === 'messages') {
          this.$store.dispatch('conversation/setUserLastSeen')
        }
        this.setUnreadView()
      })
      bus.$on(ON_UNREAD_MESSAGE_CLICK, () => {
        this.replaceRoute('messages').then(() => this.unsetUnreadView())
      })
    },
    unsetUnreadView () {
      if (this.isIFrame) {
        IFrameHelper.sendMessage({ event: 'resetUnreadMode' })
        this.setIframeHeight(false)
        this.handleUnreadNotificationDot()
      }
    },
    handleUnreadNotificationDot () {
      const { unreadMessageCount } = this
      if (this.isIFrame) {
        IFrameHelper.sendMessage({
          event: 'handleNotificationDot',
          unreadMessageCount
        })
      }
    },
    setIframeHeight (isFixedHeight) {
      this.$nextTick(() => {
        const extraHeight = getExtraSpaceToScroll()
        IFrameHelper.sendMessage({
          event: 'updateIframeHeight',
          isFixedHeight,
          extraHeight
        })
      })
    }
  }
}
</script>

<style lang="scss">
// spaces
$zero: 0;
$space-micro: 0.2rem;
$space-smaller: 0.4rem;
$space-small: 0.8rem;
$space-one: 1rem;
$space-slab: 1.2rem;
$space-normal: 1.6rem;
$space-two: 2.0rem;
$space-medium: 2.4rem;
$space-large: 3.2rem;
$space-larger: 4.8rem;
$space-jumbo: 6.4rem;
$space-mega: 10.0rem;
</style>
